﻿
using Microsoft.WindowsAPICodePack.ShellExtensions.Interop;
using MobileControlGuru.AutoTask;
using MobileControlGuru.Base;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MobileControlGuru.AutoTask.TaskJson;

namespace MobileControlGuru.Src
{
    /// <summary>
    /// 设备job
    /// </summary>
    public class DeviceCtrlJob : IJob
    {

        public TaskJson.TaskInfo taskInfo;

        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                // 在这里编写您的作业逻辑
                //MessageBox.Show("作业执行了!");
                IJobDetail jobDetail = context.JobDetail;
                JobDataMap dataMap = context.MergedJobDataMap;

                //var tasks = new List<Task>();
                Console.WriteLine($"jobb task is started ：{DateTime.Now}");
                bool iscontainkey = dataMap.ContainsKey("taskinfo");
                if (iscontainkey)
                {
                    string taskinfojsonstring = dataMap.GetString("taskinfo");
                    this.taskInfo = JsonConvert.DeserializeObject<TaskInfo>(taskinfojsonstring);

                    if (this.taskInfo.DeviceName.Length > 0)
                    {
                      
                        for (int i = 0; i < this.taskInfo.DeviceName.Length; i++)
                        {
                            string devicename = this.taskInfo.DeviceName[i];
                            //logForm.AppendLog($"Job executed at{devicename}- {DateTime.Now}");
                            Console.WriteLine($"jobb task is started devicename ：{devicename}");
                            TaskRun taskRun = new TaskRun(devicename, this.taskInfo, true);

                            Task task = new System.Threading.Tasks.Task(() =>
                            {
                                taskRun.Run();

                            }, taskRun.cts.Token);

                            task.Start();

                        }
                        this.taskInfo.State = TaskStateEnum.run;

                        //已完成。。。。。。
                        Console.WriteLine($"jobb task is done ：{DateTime.Now}");
                    }

                }
                //// 检查作业是否成功执行，如果没有异常

            }
            catch (Exception ex)
            {
                Tools.LogHelper.Error(ex, context.JobDetail.Key.ToString());

            }

            //// 删除作业
            //context.Scheduler.DeleteJob(context.JobDetail.Key);
            return Task.CompletedTask;
        }


    }
}
